package com.toptech.downloadmanager.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.toptech.downloadmanager.entity.ThreadInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * 数据库接口的实现
 * 
 * @author zhengshaorui
 * 
 */
public class DBThreadListenerImp implements DBThreadListener {
	private DBhelper mDBhelper = null;

	public DBThreadListenerImp(Context context) {
		// 在接口实现的时候，创建数据库表
		mDBhelper =  DBhelper.Holder.getInstance();
	}


	public synchronized void insertThread(ThreadInfo threadInfo) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = mDBhelper.getWritableDatabase();
		db.execSQL(
				"insert into thread_info(thread_id,url,start,end,finished) values(?,?,?,?,?)",
				new Object[] {threadInfo.getId(), threadInfo.getUrl(),
						threadInfo.getStart(), threadInfo.getEnd(),
						threadInfo.getFinished() });
		db.close();

	}

	@Override
	public synchronized void deleteThread(String url) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = mDBhelper.getWritableDatabase();
		db.execSQL("delete from thread_info where url = ?",
				new Object[] { url });
		db.close();
	}

	@Override
	public synchronized void updateThread(String url, int thread_id, long finished) {
		// TODO Auto-generated method stub

		SQLiteDatabase db = mDBhelper.getWritableDatabase();
		db.execSQL(
				"update thread_info set finished = ? where url = ? and thread_id = ?",
				new Object[] { finished, url, thread_id });
		db.close();
	}

	/**
	 * @param url
	 * @return
     */
	public synchronized List<ThreadInfo> getThreads(String url) {
		List<ThreadInfo> mList = new ArrayList<ThreadInfo>();
		SQLiteDatabase db = mDBhelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from thread_info where url = ?",
				new String[] { url });
		if (cursor.moveToFirst()) {
			do {
				ThreadInfo mThreadInfo = new ThreadInfo();
				mThreadInfo.setUrl(cursor.getString(cursor
						.getColumnIndex("url")));
				mThreadInfo.setId(cursor.getInt(cursor.getColumnIndex("thread_id")));
				mThreadInfo.setStart(cursor.getInt(cursor
						.getColumnIndex("start")));
				mThreadInfo.setEnd(cursor.getInt(cursor.getColumnIndex("end")));
				mThreadInfo.setFinished(cursor.getInt(cursor
						.getColumnIndex("finished")));
				mList.add(mThreadInfo);
			} while (cursor.moveToNext());
		}
		db.close();
		cursor.close();
		return mList;
	}

	@Override
	public synchronized boolean isThreadExsits(String url, int thread_id) {
		boolean isExsits = false;
		SQLiteDatabase db = mDBhelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"select * from thread_info where url = ? and thread_id = ?",
				new String[] { url, thread_id + "" });

		isExsits = cursor.moveToNext();
		db.close();
		cursor.close();
		return isExsits;
	}

}
